#!/bin/bash

# Repository Clone Script
# Function: Clone demo Git repository to workspace

# Set UTF-8 encoding support
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# Detect operating system type
OS_TYPE=$(uname -s)
echo "Detected operating system: $OS_TYPE"

# ============================================
# Configuration and Global Variables
# ============================================

# Set working directory
if [ "$OS_TYPE" = "Darwin" ]; then
    # For macOS
    export AWS="${AWS:-/Users/$(whoami)/workspace}"
elif [ "$OS_TYPE" = "Linux" ]; then
    # For Linux
    export AWS="${AWS:-/home/$(whoami)/workspace}"
else
    # Original logic for other systems
    export AWS="${AWS:-/c/Users/$(whoami)/workspace}"
    # If in Windows environment, different path format may be needed
    case "$(uname -s)" in
        MINGW*|CYGWIN*)
            export AWS="${AWS:-c:/Users/$(cmd.exe /c echo %USERNAME% | tr -d '\r')/workspace}"
            ;;
    esac
fi

# Repository path and URL
REPO_PATH="$AWS/demo"
REPO_URL="git@gitee.com:xx252016_admin/demo.git"

# ============================================
# Utility Functions
# ============================================

# Log function
log() {
    local level=$1
    local message=$2
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local level_str
    
    case $level in
        0) level_str="ERROR" ;;
        1) level_str="WARN"  ;;
        2) level_str="INFO"  ;;
        3) level_str="DEBUG" ;;
        *) level_str="UNKNOWN" ;;
    esac
    
    if [ $level -le 2 ]; then
        echo "[$timestamp] [$level_str] $message"
    fi
}

# Check if command exists
check_command() {
    local cmd=$1
    local desc=$2
    
    if ! command -v "$cmd" > /dev/null 2>&1; then
        log 0 "Error: Command $cmd ($desc) not found, please install it first."
        return 1
    fi
    return 0
}

# Create directory
create_dir() {
    local dir_path=$1
    
    if [ ! -d "$dir_path" ]; then
        log 2 "Creating directory: $dir_path"
        mkdir -p "$dir_path" || {
            log 0 "Error: Failed to create directory $dir_path"
            return 1
        }
    fi
    return 0
}

# Clone single repository
clone_repo() {
    log 2 "Cloning demo repository: $REPO_PATH"
    
    # Create parent directory
    create_dir "$(dirname "$REPO_PATH")" || return 1
    
    # If directory exists, check if it's a Git repository
    if [ -d "$REPO_PATH" ]; then
        if [ -d "$REPO_PATH/.git" ]; then
            log 1 "Warning: Repository directory already exists and is a Git repository, skipping clone $REPO_PATH"
            return 0
        else
            log 1 "Warning: Repository directory exists but is not a Git repository, deleting and re-cloning $REPO_PATH"
            rm -rf "$REPO_PATH" || {
                log 0 "Error: Failed to delete existing directory $REPO_PATH"
                return 1
            }
        fi
    fi
    
    # Show Git version information for debugging
    git --version
    
    # Clone repository
    log 2 "Executing clone: git clone --verbose -b master $REPO_URL $REPO_PATH"
    git clone --verbose -b master "$REPO_URL" "$REPO_PATH" || {
        log 0 "Error: Repository clone failed $REPO_URL"
        log 0 "Please check the following:"
        log 0 "1. SSH key is correctly configured"
        log 0 "2. Remote repository is accessible"
        log 0 "3. Network connection is normal"
        return 1
    }
    
    log 2 "Repository clone completed: $REPO_PATH"
    return 0
}

# Show help information
show_help() {
    echo "Repository Clone Tool"
    echo "Usage: $0 [options]"
    echo ""
    echo "Function: Clone demo Git repository to workspace"
    echo ""
    echo "Options:"
    echo "  --help, -h        Show this help information"
    echo "  --all             Clone demo repository (default behavior)"
    echo ""
}

# ============================================
# Main Program
# ============================================

# Parse command line arguments
ACTION="all"

while [ $# -gt 0 ]; do
    case $1 in
        --help|-h)
            show_help
            exit 0
            ;;
        --all)
            ACTION="all"
            shift
            ;;
        *)
            log 0 "Unknown parameter: $1"
            show_help
            exit 1
            ;;
    esac
done

# Execute corresponding action
case "$ACTION" in
    "all")
        # Check git command
        check_command git "Git version control tool" || exit 1
        
        # Create working directory
        create_dir "$AWS" || exit 1
        
        # Clone repository
        clone_repo
        ;;
    *)
        log 0 "Unknown action: $ACTION"
        exit 1
        ;;
esac

exit $?